import cn.edu.dgut.Entity.User;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/changeInfo")
public class ChangeInfoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String,String> infoMap = (Map<String, String>) request.getSession().getAttribute("isLogin");
        String user_number = infoMap.get("user_number");
        //根据工号查找用户
        String name = request.getParameter("name");
        String phone_number = request.getParameter("phone_number");
        String email = request.getParameter("email");
        String faculty_title = request.getParameter("faculty_title");
        String group = request.getParameter("group");
        if(name.trim().equals("null")){
            name=null;
        }
        if(phone_number.trim().equals("null")){
            phone_number=null;
        }
        if(email.trim().equals("null")){
            email=null;
        }
        if(faculty_title.trim().equals("null")){
            faculty_title=null;
        }
        if(group.trim().equals("null")){
            group=null;
        }
        /*user.setName(name);
        user.setPhone_number(phone_number);
        user.setEmail(email);
        user.setFaculty_title(faculty_title);
        user.setGroup(group);
        new ReadFile().resetUserInfo(user);//写入文件中*/

        EntityManager em = (EntityManager) request.getAttribute("_entity.manager");
        String jpql = "select u from User u where u.user_number = :number";
        Query query = em.createQuery(jpql);
        query.setParameter("number",user_number);
        User user = (User)query.getSingleResult();
        user.setPhone_number(phone_number);
        user.setEmail(email);
        user.setFaculty_title(faculty_title);
        user.setType(group);
        em.persist(user);

        response.sendRedirect("/info.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
